package db10;

public class ProducerConsumer {
    static class BoundedBuffer{
        private final int capacity = 10;

        private int [] buffer = new int[capacity];

        private  int count = 0;

        public synchronized void produce(){
            while (count ==capacity){
                try{
                    wait();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.out.println("生产者被中断");
                }
            }
            buffer [count++] = (int) (Math.random()* 100);

            System.out.println("生产者生产了一个产品，当前数量："+count);

            notifyAll();
        }

        public synchronized  void consum() throws InterruptedException{
            while (count == 0){
                wait();
            }
            int produce = buffer[--count];

            System.out.println("消费者消费了一个产品，当前数量："+ count);

            notifyAll();
        }
    }

    public static void main(String[] args) {

        BoundedBuffer buffer = new BoundedBuffer();

        Thread producer = new Thread(() ->{
            for (int i = 0; i < 20; i++) {
                buffer.produce();
            }
        });
        Thread consumer = new Thread(() ->{
            for (int i = 0; i <20 ; i++) {
                try{
                    buffer.consum();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        producer.start();
        consumer.start();

        try {
            producer.join();
            consumer.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
